package happy.town.case_JdbcUtils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

public class JdbcUtils02 {
    static InputStream is = null;
    static Properties properties = new Properties();

    static {
        try {
            is = JdbcUtils02.class.getResourceAsStream("db.properties");
            try {
                //将流加载到文件中
                properties.load(is);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Class.forName(properties.getProperty("driverClassName"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //获取连接(自己决定，封装到方法中)
    //static静态，直接使用类名.方法名更方便
    public static Connection getconnection() throws Exception {
        String url = properties.getProperty("url");
        String user = properties.getProperty("username");
        String password = properties.getProperty("password");
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

    //释放资源
    public static void release(ResultSet rs, PreparedStatement pstm, Connection conn) throws Exception {
        if (rs != null) {
            rs.close();
        }
        if (pstm != null) {
            pstm.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}
